﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Model;
using ModelDto;


namespace CodeFirst
{
    public class MyDbContext : DbContext
    {
        public DbSet<PurchaseOrder> PurchaseOrder { get; set; }
        public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
        {
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //IOC已经注入链接字符串，这里就不用写连接字符串了
            //引入sql连接
            //optionsBuilder.UseMySql(strConn, ServerVersion.AutoDetect(strConn));
            //optionsBuilder.UseSqlServer(strConn);
            //每次查询控制台打印EF表达式对应的SQL语句
            optionsBuilder.UseLoggerFactory(LoggerFactory.Create(builder =>
            {
                builder.AddConsole();
            }));

        }
        //审计
        public override int SaveChanges()
        {
            ChangeTracker.DetectChanges(); // 确保所有更改都已被检测到  
            //需要审计的类继承IAuditableEntity
            //var auditableEntities = ChangeTracker.Entries<IAuditableEntity>()
            //    .Where(e => e.State == EntityState.Modified || e.State == EntityState.Added || e.State == EntityState.Deleted)
            //    .ToList();
            var entitiesWithChanges = ChangeTracker.Entries()
                .Where(e => e.State == EntityState.Modified || e.State == EntityState.Added || e.State == EntityState.Deleted)
                //.Where(e => e.Entity.GetType() == typeof(PurchaseOrder)) //只审计PurchaseOrder实体
                .ToList();

            foreach (var entityEntry in entitiesWithChanges)
            {
                if (entityEntry.State == EntityState.Modified || entityEntry.State == EntityState.Added)
                {
                    // 对于Modified和Added状态，我们可以获取原始值和当前值  
                    foreach (var property in entityEntry.Properties)
                    {
                        if (property.IsModified) // 仅针对已修改的属性  
                        {
                            var originalValue = property.OriginalValue;
                            var currentValue = property.CurrentValue;

                            // 输出原始值和当前值（或执行其他逻辑）  
                            Console.WriteLine($"Entity: {entityEntry.Entity.GetType().Name}, Property: {property.GetType().Name}, Original Value: {originalValue}, Current Value: {currentValue}");
                        }
                    }
                }
                else if (entityEntry.State == EntityState.Deleted)
                {
                    // 对于Deleted状态，通常我们只关心当前值（因为实体即将被删除）  
                    // 但你也可以从快照或其他来源获取原始值（如果可用）  
                    var entityType = entityEntry.Entity.GetType();
                    foreach (var propertyInfo in entityType.GetProperties())
                    {
                        var currentValue = propertyInfo.GetValue(entityEntry.Entity);
                        // 注意：对于Deleted状态，OriginalValue可能不可用或为空  
                        // 你可能需要从其他地方获取原始值，比如审计日志或之前的查询结果  
                        Console.WriteLine($"Entity: {entityType.Name}, Property: {propertyInfo.Name}, Current (Deleted) Value: {currentValue}");
                    }
                }
            }

            // 调用基类的SaveChanges来实际保存更改  
            return base.SaveChanges();
        }

        // 如果你使用异步保存，你也需要重写SaveChangesAsync方法  
        public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            ChangeTracker.DetectChanges(); // 确保所有更改都已被检测到  

            var entitiesWithChanges = ChangeTracker.Entries()
                .Where(e => e.State == EntityState.Modified || e.State == EntityState.Added || e.State == EntityState.Deleted)
                .ToList();

            foreach (var entityEntry in entitiesWithChanges)
            {
                if (entityEntry.State == EntityState.Modified || entityEntry.State == EntityState.Added)
                {
                    foreach (var property in entityEntry.Properties)
                    {
                        if (property.IsModified)
                        {
                            var originalValue = property.OriginalValue;
                            var currentValue = property.CurrentValue;

                            // 输出原始值和当前值（或执行其他逻辑）  
                            Console.WriteLine($"Entity: {entityEntry.Entity.GetType().Name}, Property: {property.GetType().Name}, Original Value: {originalValue}, Current Value: {currentValue}");
                        }
                    }
                }
                else if (entityEntry.State == EntityState.Deleted)
                {
                    var entityType = entityEntry.Entity.GetType();
                    foreach (var propertyInfo in entityType.GetProperties())
                    {
                        var currentValue = propertyInfo.GetValue(entityEntry.Entity);
                        Console.WriteLine($"Entity: {entityType.Name}, Property: {propertyInfo.Name}, Current (Deleted) Value: {currentValue}");
                    }
                }
            }

            // 调用基类的SaveChangesAsync来实际异步保存更改  
            return await base.SaveChangesAsync(cancellationToken);
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<PurchaseOrder>().ToTable($"yw_PurchaseOrder");
        }
    }
}
